package com.ndkj.rpcserver.protocol;

import com.ndkj.rpcserver.common.dto.Invocation;
import com.ndkj.rpcserver.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

public class HttpServletHandler {

    /**
     * 泛化调用
     */
    public void handler(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Invocation invoker = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();
            String interfaceName = invoker.getInterfaceName();
            Class clazz = LocalRegister.get(interfaceName, invoker.getVersion());

            Method method = clazz.getMethod(invoker.getMethodName(), invoker.getParameterTypes());
            String res = (String) method.invoke(clazz.newInstance(), invoker.getParameters());
            IOUtils.write(res, resp.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
